package com.nexus.web.sys.Nexus;

import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @Date 2025/9/23 13:08
 * @Author luzhengning
 **/
@Component
@Slf4j
public class SpringRabbitListener {

    @SneakyThrows
    @RabbitListener(queues = "order.queue",errorHandler = "nexusRabbitErrorHandler")
    public void onMessage(Message message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        // 处理消息
        String messageBody = new String(message.getBody());
        // 业务处理
        // 手动确认消息
        channel.basicAck(deliveryTag, false);
        // 或者拒收重回队列
        channel.basicReject(deliveryTag, true);
    }

    private void processMessage(String message) {
        // 模拟业务处理
        if (message.contains("error")) {
            throw new RuntimeException("模拟业务异常");
        }
    }

    /**
     * 根据重试次数决定确认策略
     */
//    private void handleConsumeFailure(Message message, Channel channel, Exception e,
//                                      String businessId, long deliveryTag) throws Exception {
//        int retryCount = getRetryCount(message);
//        int maxRetry = properties.getRetry().getMaxAttempts();
//
//        if (retryCount < maxRetry) {
//            // 拒绝消息并重新入队
//            channel.basicNack(deliveryTag, false, true);
//            log.warn("消息处理失败，已拒绝并重新入队 - 重试次数: {}, businessId: {}",
//                    retryCount, businessId, e);
//        } else {
//            // 达到最大重试次数，拒绝并不重新入队（进入死信队列）
//            channel.basicNack(deliveryTag, false, false);
//            deadLetterHandler.handleDeadLetter(message, e, businessId);
//            log.error("消息处理失败，已达到最大重试次数，进入死信队列 - businessId: {}",
//                    businessId, e);
//        }
//    }

    /**
     * 获取重试次数
     */
    private int getRetryCount(Message message) {
        Map<String, Object> headers = message.getMessageProperties().getHeaders();
        Object retryCountHeader = headers.get("x-retry-count");
        if (retryCountHeader instanceof Integer) {
            return (Integer) retryCountHeader;
        }
        return 0;
    }
}